package com.lucas.test.service;

import com.lucas.spring.annotation.Component;
import com.lucas.spring.interfaces.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author: LiuCheng
 * @description:
 * @date: 2023-11-26 14:05
 **/

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {



    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println(bean+"初始化前----------------");
        if(beanName.equals("userService")){
            System.out.println("还没修改时名字为-----------"+((UserService)bean).getName());
            ((UserService)bean).setName("lucas");
            System.out.println("成功修改了userService的name属性为：--------"+((UserService)bean).getName());
        }

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println(bean+"初始化后----------------");
        System.out.println();

        if(beanName.equals("studentService")){
            Object proxyInstance = Proxy.newProxyInstance(MyBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                    System.out.println("正在执行代理逻辑-----------------");

                    return method.invoke(bean,args);
                }
            });
            return proxyInstance;
        }
        return bean;
    }
}
